package com.example.config.httpclient;

import com.example.pojo.model.GiteeConfig;
import com.example.pojo.model.req.GiteeAccessTokenReq;
import com.example.pojo.model.resp.GiteeAccessTokenResp;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * Gitee 获取 AccessToken 的 http 请求
 */
@Component
public class GiteeAccessClient {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private GiteeConfig config;

    public GiteeAccessTokenResp getAccessToken(String code,String state) {
        //构建 restTemplate.exchange 所需参数
        String url = config.getTokenUrl();
        HttpMethod method = HttpMethod.POST;
        GiteeAccessTokenReq body = GiteeAccessTokenReq.builder()
                .grant_type("authorization_code")
                .redirect_uri(config.getRedirectUri())
                .code(code)
                .client_id(config.getClientId())
                .client_secret(config.getClientSecret())
                .build();
        HttpEntity requestEntity = new HttpEntity(body);
        Class<GiteeAccessTokenResp> responseType = GiteeAccessTokenResp.class;

        //发起 HTTP 请求
        ResponseEntity<GiteeAccessTokenResp> resp = restTemplate.exchange(url, method, requestEntity, responseType);

        //响应
        GiteeAccessTokenResp giteeAccessTokenResp = resp.getBody();
        return giteeAccessTokenResp;
    }

}
